﻿/* dk2Repository - Copyright (C) 2011 Daniel Kuczewski http://www.dk2.de/

 * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA */

using System;
using System.Collections.Generic;

namespace dk2Database
{
    /// <summary>
    /// Manages database pool
    /// </summary>
    public static class Databases
    {
        private static string _defaultDatabaseName;
        private static readonly Dictionary<string, Database> _databases;


        public static Database Default
        {
            get
            {
                if (!_databases.ContainsKey(_defaultDatabaseName))
                    throw new Exception("No default database registered");

                return _databases[_defaultDatabaseName];
            }
        }

        static Databases()
        {
            _defaultDatabaseName = "";
            _databases = new Dictionary<string, Database>();
        }

        public static void RegisterDefault(Database db)
        {
            Register("default", db);
        }

        public static void Register(string databasename, Database db)
        {
            if (_databases.ContainsKey(databasename))
            {
                _databases[databasename].Dispose();
                _databases.Remove(databasename);
            }

            _databases.Add(databasename, db);

            if (string.IsNullOrEmpty(_defaultDatabaseName))
                _defaultDatabaseName = databasename;
        }

        public static void SetDefault(string databasename)
        {
            if (!_databases.ContainsKey(databasename))
                throw new Exception(databasename + " not registered");

            _defaultDatabaseName = databasename;
        }

        public static Database Get(string databasename)
        {
            if (!_databases.ContainsKey(databasename))
                throw new ArgumentException(databasename + " not registered");

            return _databases[databasename];
        }

         public static void Dispose()
         {
             foreach (var database in _databases)
                 database.Value.Dispose();

             _databases.Clear();
         }

    }
}
